package cn.ynrcb.personnelfile.admin.controller;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.*;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.RandomUtil;
import cn.ynrcb.personnelfile.admin.entity.FileEntity;
import cn.ynrcb.personnelfile.common.annotation.BusinessLog;
import com.github.xiaoymin.knife4j.annotations.ApiOperationSupport;
import com.github.xiaoymin.knife4j.annotations.DynamicParameter;
import com.github.xiaoymin.knife4j.annotations.DynamicResponseParameters;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;

import cn.ynrcb.personnelfile.admin.entity.PersonnelInfoEntity;
import cn.ynrcb.personnelfile.admin.service.PersonnelInfoService;
import cn.ynrcb.personnelfile.common.utils.PageUtils;
import cn.ynrcb.personnelfile.common.utils.R;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;


/**
 * 
 *
 * @author wujianfan
 * @email fanxipo@qq.com
 * @date 2023-08-22 00:17:26
 */
@RestController
@RequestMapping("admin/personnelinfo")
public class PersonnelInfoController {
    @Autowired
    private PersonnelInfoService personnelInfoService;
    @Value("${uploadFilePath}")
    private String uploadFilePath;

    /**
     * 档案照片文件上传
     *
     * @param file
     * @param req
     * @return
     */
    @ApiOperation("档案照片文件上传")
    @ApiImplicitParams({
    })
    @ApiOperationSupport(
            responses = @DynamicResponseParameters(properties = {
                    @DynamicParameter(value = "状态码", name = "code", example = "0"),
                    @DynamicParameter(value = "信息", name = "message", example = "success"),
            })
    )
    @BusinessLog("档案照片文件上传")
    @PostMapping("/upload")
    @RequiresPermissions("admin:personnelinfo:upload")
    public Map<String, Object> fileUpload(MultipartFile file, HttpServletRequest req) {
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy/MM/dd/");
        Map<String, Object> resultMap = new HashMap<>();
        // 得到上传时的文件名
        String originName = file.getOriginalFilename();
        String strFormat = simpleDateFormat.format(new Date());
        String realPath = uploadFilePath + strFormat;
        File folder = new File(realPath);
        if (!folder.exists()) {
            folder.mkdirs();
        }
        // 保存文件对象，加上uuid是为了防止文件重名
        String strNewFileName = UUID.randomUUID().toString().replaceAll("-", "") + originName.substring(originName.lastIndexOf("."));
        try {
            file.transferTo(new File(folder, strNewFileName));
            String strUrl = req.getScheme() + "://" + req.getServerName() + ":" + req.getServerPort() + "/" + strFormat + strNewFileName;
            resultMap.put("code", "0");
            resultMap.put("status", "success");
            resultMap.put("url", strUrl);
            resultMap.put("filePath", "/" + strFormat + strNewFileName);
            resultMap.put("fileName", originName);
            FileEntity vo = new FileEntity();
            vo.setId(RandomUtil.randomUUID().replaceAll("-", ""));
            vo.setFileName(originName);
            vo.setFilePath("/" + strFormat + strNewFileName);
            personnelInfoService.saveFile(vo.getId(), vo.getFileName(), vo.getFilePath());
            resultMap.put("fileId", vo.getId());
        } catch (IOException e) {
            e.printStackTrace();
            resultMap.put("status", "error");
            resultMap.put("msg", e.getMessage());
        }
        return resultMap;
    }

    /**
     * 文件真删
     *
     * @param id
     * @return
     */
    @ApiOperation("文件真删")
    @ApiImplicitParams({
    })
    @ApiOperationSupport(
            responses = @DynamicResponseParameters(properties = {
                    @DynamicParameter(value = "状态码", name = "code", example = "0"),
                    @DynamicParameter(value = "信息", name = "message", example = "success"),
            })
    )
    @BusinessLog("文件真删")
    @GetMapping("/deleteFile/{id}")
    @RequiresPermissions("admin:personnelinfo:deleteFile")
    public R deleteFile(@PathVariable("id") String id) {
        FileEntity entity = personnelInfoService.getFileById(id);
        String s = uploadFilePath.substring(0, uploadFilePath.length() - 1) + entity.getFilePath();
        FileUtil.del(new File(s));
        personnelInfoService.deleteByFileId(id);
        return R.ok();
    }

    /**
     * 列表
     */
    @RequestMapping("/list")
    @RequiresPermissions("admin:personnelinfo:list")
    public R list(@RequestParam Map<String, Object> params){
        PageUtils page = personnelInfoService.queryPage(params);

        return R.ok().put("page", page);
    }


    /**
     * 信息
     */
    @RequestMapping("/info/{id}")
    @RequiresPermissions("admin:personnelinfo:info")
    public R info(@PathVariable("id") Long id){
		PersonnelInfoEntity personnelInfo = personnelInfoService.getById(id);

        return R.ok().put("personnelInfo", personnelInfo);
    }

    /**
     * 保存
     */
    @RequestMapping("/save")
    @RequiresPermissions("admin:personnelinfo:save")
    public R save(@RequestBody PersonnelInfoEntity personnelInfo){
		personnelInfoService.save(personnelInfo);

        return R.ok();
    }

    /**
     * 修改
     */
    @RequestMapping("/update")
    @RequiresPermissions("admin:personnelinfo:update")
    public R update(@RequestBody PersonnelInfoEntity personnelInfo){
		personnelInfoService.updateById(personnelInfo);

        return R.ok();
    }

    /**
     * 删除
     */
    @RequestMapping("/delete")
    @RequiresPermissions("admin:personnelinfo:delete")
    public R delete(@RequestBody Long[] ids){
		personnelInfoService.removeByIds(Arrays.asList(ids));

        return R.ok();
    }

}
